package hr.ctg.domain.action.otok;

import hr.ctg.domain.model.Otok;
import hr.ctg.domain.model.Rola.Role;
import hr.ctg.service.dao.OtokDAO;
import hr.web.jsf.model.PagedListDataModel;

import java.util.ArrayList;
import java.util.List;

import org.jboss.seam.annotations.Factory;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.web.RequestParameter;
import org.jboss.seam.security.Identity;

@Name(value = "otokSearch")
public class OtokSearchAction {
	@In
	private OtokDAO otokDAO;
	@In
	private Identity identity;
	@In
	private String currentLang;

	@RequestParameter
	Integer page;

	// @Logger
	// private Log log;

	private List<Otok> tmpList;

	@Factory("otoci")
	public javax.faces.model.DataModel getOtoci() {
		if (page == null) {
			page = 1;
		}
		if (null == tmpList) {
			if (identity.hasRole(Role.ADMIN.toString())) {
				tmpList = otokDAO.findAllOByNaziv(page * 15 - 15, 15);
			} else {
				tmpList = otokDAO.findByObjOpObjJezik(currentLang,
						page * 15 - 15, 15);
			}
		}

		return new PagedListDataModel(tmpList, otokDAO
				.findCountByObjOpObjJezik(currentLang), 15);
	}

	/*
	 * @Factory("otociByFirstLetter") public void getOtokWithFirstLetter() {
	 * otociByFirstLetter = otokDAO.findByFirstLetter(letter); }
	 */

	public List<Otok> getOtoci(final String letter) {
		if (null == tmpList) {
			if (identity.hasRole(Role.ADMIN.toString())) {
				tmpList = otokDAO.findByFirstLetter(letter);
			} else {
				tmpList = otokDAO.findByFirstLetterObjOpObjJezik(letter,
						currentLang);
			}

		}
		return getCashedOtoci(letter);
	}

	@Factory("firstOtociLetters")
	public List<String> getFirstLetters() {
		if (identity.hasRole(Role.ADMIN.toString())) {
			return otokDAO.findFirstLetters();
		} else {
			return otokDAO.findFirstLettersByObjOpObjJezik(currentLang);
		}
	}

	public List<Otok> getCashedOtoci(final String letter) {
		List<Otok> otoci = new ArrayList<Otok>();
		for (Otok o : tmpList) {
			if (o.getNaziv().startsWith(letter))
				otoci.add(o);
		}
		return otoci;
	}
}
